from flask_restplus import Namespace, Resource
from app.extensions import db
from app.models import User
from flask import request
from werkzeug.security import generate_password_hash
from .auth import auth, g

api = Namespace('user', description='用户资源')

doc = {
    'params': {'page': '页码'},   # GET参数
    'description': '描述',        # 描述
    'responses': {403: 'forbidden', 404: 'page not found'},     # 响应
    # 'deprecated': True  # 是否废弃
}


# doc：添加接口文档信息
@api.route('/pwd_change/', doc=doc)
class UserAPI(Resource):
    @auth.login_required
    def put(self):
        user = User.query.filter_by(username=g.data['username']).first()
        if user:
            user.password = generate_password_hash(request.form.get('password'))
        return '密码修改成功'


class UserListAPI(Resource):
    def post(self):
        name = request.form.get('name')
        username = request.form.get('username')
        password = generate_password_hash(request.form.get('password'))
        age = request.form.get('age')
        user = User(name=name, username=username, password=password, age=age)
        db.session.add(user)
        return '已注册成功'


api.add_resource(UserListAPI, '/register/')